package common.exceptions;

import ex2.Token;
import fun.parser.earley.EarleyParser;

/**
 * Created with IntelliJ IDEA.
 * User: Roi
 * Date: 11/20/13
 */
public class ParseException extends Exception {

    private String message;

    public ParseException(EarleyParser.PostMortem postMortem) {
        buildMessage(postMortem);
    }

    public ParseException(String message) {
        this.message = message;
    }

    @Override
    public String getMessage() {
        return message;
    }

    private void buildMessage(EarleyParser.PostMortem postMortem) {
        String expectedStr = "syntax error; expected";
        String foundStr = "";
        String locStr = "";
        String endStr = "";

        if (postMortem.token != null) {
            locStr = ((Token)postMortem.token).getLine()
                    + ":"
                    + ((Token)postMortem.token).getColumn()
                    + " : ";

            foundStr += ", but found '"
                    + postMortem.token.tag
                    + "'";
        }
        else {
            endStr = "at end of input : ";
        }

        int count = 1;
        for (String str : postMortem.expecting) {
            expectedStr += " '" + str + "'";

            if (count != postMortem.expecting.size())
                expectedStr += " or";

            ++count;
        }

        if (endStr.isEmpty())
            message = locStr + expectedStr + foundStr;
        else
            message = endStr + expectedStr;
    }
}
